package com.trendytech.tds.common.filter;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;


public class LoginHandler implements AuthenticationSuccessHandler {
/*	@Autowired
	private IUserService userService;*/
	
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication)
			throws IOException, ServletException {
		String url = "/index.jsp";

		SecurityContext securityContext = SecurityContextHolder.getContext();
		String userName = securityContext.getAuthentication().getName();
		HttpSession session = request.getSession();
		session.setAttribute("userName", userName);
		String ip=getIpAddr(request);
		//request.getSession().setAttribute("userName", userName);
		com.trendytech.tds.entity.User user = null;
		if (user == null) {
			throw new UsernameNotFoundException(userName);
		}

		if (null != userName && !"".equals(userName)) {

			String userId = user.getId();
			LogRecrod logRecrod = new LogRecrod();
			logRecrod.setUserId(userId);
			logRecrod.setUserName(userName);
			logRecrod.setIp(ip);
			request.getSession().setAttribute("logRecrod", logRecrod);
		}
		response.sendRedirect(request.getContextPath() + url);
	}
	
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		return ip;
	}

}
